from flask import Blueprint, request, jsonify, render_template
from apps import db
from apps.task.models import Task

task_bp = Blueprint('task', __name__, url_prefix='/task')

@task_bp.route('/')
def index():
    return render_template('index.html')

# === API 示例：CRUD ===

# 获取所有任务
@task_bp.route('/api/tasks', methods=['GET'])
def get_tasks():
    tasks = Task.query.all()
    return jsonify([task.to_dict() for task in tasks])

# 创建任务
@task_bp.route('/api/tasks', methods=['POST'])
def create_task():
    data = request.get_json()
    if not data or 'title' not in data:
        return jsonify({'error': '缺少 title'}), 400

    task = Task(title=data['title'])
    db.session.add(task)
    db.session.commit()
    return jsonify(task.to_dict()), 201

# 更新任务
@task_bp.route('/api/tasks/<int:id>', methods=['PUT'])
def update_task(id):
    task = Task.query.get_or_404(id)
    data = request.get_json()
    task.title = data.get('title', task.title)
    task.done = data.get('done', task.done)
    db.session.commit()
    return jsonify(task.to_dict())

# 删除任务
@task_bp.route('/api/tasks/<int:id>', methods=['DELETE'])
def delete_task(id):
    task = Task.query.get_or_404(id)
    db.session.delete(task)
    db.session.commit()
    return '', 204